<script setup>
import { ref, onMounted, reactive, computed, onUnmounted } from "vue";
import { Swiper, SwiperSlide } from "swiper/vue";
import { Virtual, Mousewheel } from "swiper";
import "swiper/css";

import VideoPlayer from "../../components/VideoPlayer/VideoPlayer.vue";
import VideoInfo from "../../components/VideoPlayer/VideoInfo.vue";
import CollectionModal from "../../components/CollectionModal/index.vue";
import UserInfoAndCommentPanel from "../../components/UserInfoAndCommentPanel/index.vue";

import { getRecommendVideosApi } from "@/api/video";
import { likeVideoApi, unlikeVideoApi } from "@/api/like";
import { followUserApi, unfollowUserApi } from "@/api/follow";
import { createHistoryApi } from "@/api/history";

import { debounce } from "@/utils/index";
import { useUserStore } from "@/store/modules/user";

// 在文件顶部导入
import { useAuthGuard } from "@/hooks/useAuthGuard";
import { ElMessage } from "element-plus";

// 在 setup 函数中添加
const { authGuard } = useAuthGuard();

// 视频数据
const videos = reactive([]);

const userStore = useUserStore(); // 获取用户store实例

// 视频加载状态
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10; // 每次加载3个视频

const swiperOptions = {
  modules: [Virtual, Mousewheel],
  direction: "vertical",
  virtual: true,
  mousewheel: true,
  slidesPerView: 1,
  speed: 500,
  spaceBetween: 100,
  initialSlide: 0,
  resistanceRatio: 0,
  watchSlidesProgress: true,
  // 添加以下参数，使滑动需要更明确的手势
  touchRatio: 1,
  touchAngle: 45,
  threshold: 5, // 增加滑动阈值，需要更明确的滑动距离才触发
  touchStartPreventDefault: false, // 防止默认行为被阻止
};

const activeIndex = ref(0);
const swiperRef = ref(null);

const showCollectionModal = ref(false);
const showUserInfoAndCommentPanel = ref(false);
const currentVideoId = ref(null);

// 当用户滑动到倒数第二个视频时触发加载
const shouldLoadMore = computed(() => {
  return (
    activeIndex.value >= videos.length - 2 && !loading.value && hasMore.value
  );
});

// 获取更多推荐视频数据的API请求
const fetchMoreVideos = async () => {
  if (loading.value || !hasMore.value) return;

  loading.value = true;

  try {
    // 调用API获取随机推荐视频数据
    const response = await getRecommendVideosApi({
      count: pageSize, // 只传递需要获取的视频数量
    });

    // 检查返回的数据
    if (response && response.data && response.data.length > 0) {
      // 将API返回的数据添加到videos数组
      videos.push(...response.data);

      // 如果返回的数据条数小于pageSize，说明没有更多数据了
      if (response.data.length < pageSize) {
        hasMore.value = false;
      }
    } else {
      // 如果返回的数据为空，表示已经没有更多数据
      hasMore.value = false;
      console.log("没有更多视频了");
    }
  } catch (error) {
    console.error("加载更多视频失败:", error);
  } finally {
    loading.value = false;
  }
};
// 处理滑动变化事件
const handleSlideChange = (swiper) => {
  // 仅检查加载逻辑，不立即更新activeIndex
  if (
    swiper.activeIndex >= videos.length - 2 &&
    !loading.value &&
    hasMore.value
  ) {
    fetchMoreVideos();
  }
};

// 添加滑动开始事件处理
const handleSlideChangeStart = () => {
  // 可以在这里暂停当前视频，防止多视频同时播放
  // 但注意不要修改activeIndex
};

// 添加滑动过渡结束事件处理器
const handleTransitionEnd = (swiper) => {
  const newIndex = swiper.activeIndex;

  // 只有在索引确实改变时才更新
  if (newIndex !== activeIndex.value) {
    // 延迟更新索引，确保DOM完全渲染并避免可能的竞态条件
    setTimeout(() => {
      activeIndex.value = newIndex;

      // 如果面板正在显示，则更新当前视频ID
      if (showUserInfoAndCommentPanel.value && videos[newIndex]) {
        currentVideoId.value = String(videos[newIndex].video_id);
      }
    }, 50);
  }
};

// 点赞
// 使用防抖包装点赞处理函数
const handleLikeDebounced = debounce(async (videoId) => {
  const video = videos.find((v) => v.video_id === videoId);

  if (!video) {
    console.error("找不到对应视频:", videoId);
    return;
  }

  // 记录之前的状态以便回滚
  const previousLikeState = video.isLiked;
  const previousLikeCount = video.likeCount;

  try {
    // 先更新本地状态，让用户立即看到反馈
    video.isLiked = !previousLikeState;
    video.likeCount += video.isLiked ? 1 : -1;

    // 调用相应的API
    if (video.isLiked) {
      await likeVideoApi(videoId);
    } else {
      await unlikeVideoApi(videoId);
    }
  } catch (error) {
    // 发生错误时恢复原状态
    console.error("点赞操作失败:", error);
    video.isLiked = previousLikeState;
    video.likeCount = previousLikeCount;
  }
}, 300);

// 点赞处理函数
const handleLike = (videoId) => {
  authGuard(() => handleLikeDebounced(videoId), {
    message: "登录后才能点赞视频",
  });
};

// 修改评论处理函数
const handleComment = (videoId) => {
  if (showUserInfoAndCommentPanel.value) {
    showUserInfoAndCommentPanel.value = false;
    return;
  }

  authGuard(
    () => {
      console.log("评论视频:", videoId);
      currentVideoId.value = String(videoId);
      showUserInfoAndCommentPanel.value = true;
    },
    {
      message: "登录后才能评论视频",
    }
  );
};

// 2 将当前视频传递给面板组件
const currentVideo = computed(() => {
  if (!currentVideoId.value) return null;
  return videos.find((v) => v.video_id == currentVideoId.value) || null;
});

// 收藏
const handleFavorites = (videoId) => {
  authGuard(
    () => {
      currentVideoId.value = String(videoId);
      showCollectionModal.value = true;
    },
    {
      message: "登录后才能收藏视频",
    }
  );
};

const handleCollect = async (selectedCollections) => {
  console.log("收藏到收藏夹:", selectedCollections, currentVideoId.value);
  if (!currentVideoId.value || selectedCollections.length === 0) return;

  const video = videos.find((v) => v.video_id == currentVideoId.value);
  if (!video) return;
  console.log("video", video);
  try {
    // 视频已添加到收藏夹，更新UI状态
    console.log(
      `视频${currentVideoId.value}已添加到收藏夹:`,
      selectedCollections
    );

    // 可以更新视频的收藏状态和计数（如果需要）
    video.isFavorited = true;
    video.favoritesCount += 1;

    // 可以显示成功提示
    ElMessage.success("收藏成功");
  } catch (error) {
    console.error("处理收藏结果失败:", error);
  }
};

// 关注
// 修改关注处理函数
const handleFollow = (authorId) => {
  authGuard(
    () => {
      // 找出所有该作者的视频
      const userVideos = videos.filter((v) => v.user.id == authorId);

      // ...其余关注逻辑保持不变...
      handleFollowDebounced(authorId);
    },
    {
      message: "登录后才能关注创作者",
    }
  );
};

// 添加防抖处理函数（原来的逻辑移到这里）
const handleFollowDebounced = debounce(async (authorId) => {
  // 原先 handleFollow 中的逻辑移到这里
  const userVideos = videos.filter((v) => v.user.id == authorId);

  if (userVideos.length === 0) {
    console.error("找不到对应用户:", authorId);
    return;
  }

  // 取第一个视频的关注状态作为当前状态
  const previousFollowState = userVideos[0].isFollowed;
  const username = userVideos[0].user.username;

  try {
    // 调用相应的API
    if (!previousFollowState) {
      // 之前未关注，现在要关注
      const currentUserId = userStore.userInfo.id;
      await followUserApi(currentUserId, authorId);
      ElMessage.success(`已关注 ${username}`);
    } else {
      // 之前已关注，现在要取消关注
      const currentUserId = userStore.userInfo.id;
      await unfollowUserApi(currentUserId, authorId);
      ElMessage.success(`已取消关注 ${username}`);
    }
    // 更新所有该作者视频的关注状态
    userVideos.forEach((video) => {
      video.isFollowed = !previousFollowState;
    });
  } catch (error) {
    // 错误处理逻辑保持不变
    if (error.message == "不能关注自己") {
    } else {
      console.error("关注操作失败:", error);
      ElMessage.error("操作失败，请稍后重试");
    }
    // 恢复所有视频的关注状态
    userVideos.forEach((video) => {
      video.isFollowed = previousFollowState;
    });
  }
}, 300);

// 添加处理评论更新事件的函数
const handleCommentUpdate = (count) => {
  if (!currentVideoId.value) return;

  // 找到当前视频对象
  const video = videos.find((v) => v.video_id == currentVideoId.value);
  if (!video) return;

  // 更新评论数
  video.commentCount = (video.commentCount || 0) + count;
};

// 关闭评论面板
const closeUserInfoAndCommentPanel = () => {
  showUserInfoAndCommentPanel.value = false;
};

// 浏览历史
const handleRecordHistory = async (videoId) => {
  try {
    // 调用API记录浏览历史
    await createHistoryApi(videoId);
    console.log(`已记录视频 ${videoId} 的浏览历史`);
  } catch (error) {
    console.error("记录浏览历史失败:", error);
  }
};

// 初始化加载视频数据
const initVideos = async () => {
  loading.value = true;
  videos.length = 0; // 清空初始模拟数据

  try {
    const response = await getRecommendVideosApi({
      count: pageSize,
    });

    if (response && response.data && response.data.length > 0) {
      // 用API返回的数据替换初始模拟数据
      videos.push(...response.data);

      // 如果返回的数据条数小于pageSize，说明没有更多数据了
      if (response.data.length < pageSize) {
        hasMore.value = false;
      }
    } else {
      console.log("没有获取到视频数据");
      hasMore.value = false;
    }
  } catch (error) {
    console.error("加载初始视频失败:", error);
  } finally {
    loading.value = false;
  }
};

// 登录成功后重新加载数据
const refreshDataAfterLogin = () => {
  console.log('refreshDataAfterLogin 登录成功后重新加载数据')

  // 重置页面状态
  page.value = 1;
  videos.length = 0; // 清空视频数据
  hasMore.value = true;

  // 重新加载视频数据
  initVideos();
};

const unsubscribe = ref(null);

onMounted(() => {
  // 组件挂载后加载初始视频数据
  initVideos();

  // 注册登录成功的回调函数
  unsubscribe.value = userStore.onLoginSuccess(refreshDataAfterLogin);
});

// 在组件卸载时取消订阅
onUnmounted(() => {
  unsubscribe.value();
});
</script>

<template>
  <div
    class="video-list"
    :class="{ 'with-comment-panel': showUserInfoAndCommentPanel }"
  >
    <swiper
      ref="swiperRef"
      v-bind="swiperOptions"
      @slideChange="handleSlideChange"
      @slideChangeTransitionStart="handleSlideChangeStart"
      @transitionEnd="handleTransitionEnd"
    >
      <swiper-slide v-for="(video, index) in videos" :key="video.video_id">
        <div class="video-slide">
          <VideoPlayer
            :src="video.oss_url"
            :poster="''"
            :autoplay="index === activeIndex"
            :muted="false"
            :loop="true"
            :controls="false"
            :is-active="index === activeIndex"
            :showControls="true"
            :record-history="true"
            :video-id="video.video_id"
            :history-threshold="0.3"
            @record-history="handleRecordHistory"
          >
            <VideoInfo
              :author="video.user"
              :description="video.description"
              :like-count="video.likeCount"
              :comment-count="video.commentCount"
              :favorites-count="video.favoritesCount"
              :is-like="video.isLiked"
              :is-favorited="video.isFavorited"
              :is-followed="video.isFollowed"
              @like="handleLike(video.video_id)"
              @comment="handleComment(video.video_id)"
              @favorites="handleFavorites(video.video_id)"
              @follow="handleFollow(video.user.id)"
              @commentUpdate="handleCommentUpdate"
            />
          </VideoPlayer>
        </div>
      </swiper-slide>
    </swiper>
    <!-- 作者信息 and 视频评论面板 -->
    <UserInfoAndCommentPanel
      :show="showUserInfoAndCommentPanel"
      :video-id="currentVideoId"
      :video="currentVideo"
      @close="closeUserInfoAndCommentPanel"
      @follow="handleFollow(currentVideo.user.id)"
      @commentUpdate="handleCommentUpdate"
    />
    <!-- 收藏弹窗 -->
    <CollectionModal
      :show="showCollectionModal"
      :video-id="currentVideoId"
      @close="showCollectionModal = false"
      @collect="handleCollect"
    />
    <!-- 加载提示 -->
    <div class="loading-indicator" v-if="loading">
      <div class="loading-spinner"></div>
      <span>加载更多视频...</span>
    </div>
    <!-- 没有更多数据提示 -->
    <div
      class="no-more"
      v-if="
        !hasMore &&
        !loading &&
        videos.length > 0 &&
        activeIndex === videos.length - 1
      "
    >
      <span>没有更多视频了</span>
    </div>
  </div>
</template>

<style scoped lang="scss">
.video-list {
  height: 100%;
  width: 100%;
  display: flex;
  position: relative;
  border-radius: 8px;
  padding: 8px;

  &.with-comment-panel {
    @media (min-width: 768px) {
      :deep(.swiper) {
        width: calc(100% - 400px);
      }
    }
  }

  :deep(.swiper) {
    height: 100%;
    width: 100%;
  }

  :deep(.swiper-slide) {
    height: 100%;
    width: 100%;
    display: flex; // 确保能正确显示视频播放器包装器
  }

  .video-slide {
    height: 100%;
    width: 100%;
    position: relative;
    overflow: hidden;
    display: flex; // 确保能正确显示视频播放器包装器
  }

  .loading-indicator {
    position: absolute;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    color: white;
    z-index: 10;
    background-color: rgba(0, 0, 0, 0.7);
    padding: 12px 24px;
    border-radius: 20px;
    pointer-events: none;

    .loading-spinner {
      width: 24px;
      height: 24px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top-color: white;
      animation: spin 1s linear infinite;
      margin-bottom: 8px;
    }

    span {
      font-size: 14px;
    }
  }

  .no-more {
    position: absolute;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    color: rgba(255, 255, 255, 0.8);
    background-color: rgba(0, 0, 0, 0.5);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    pointer-events: none;
    z-index: 10;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }
}
</style>
